import type { SelectProps } from 'antd';
import { Select } from 'antd';
import lodash from 'lodash';
import { useEffect, useMemo, useState } from 'react';

interface MaxNumSelectProps {
  maxLength: number;
  options: { value: any; label: any; disabled?: boolean }[];
  value?: any[];
  onChange?: (value: any) => any;
  originProps?: Omit<SelectProps, 'value' | 'options'>;
}
const MaxNumSelect = (props: MaxNumSelectProps) => {
  const {
    maxLength,
    options = [],
    value = [],
    onChange,
    originProps,
    ...otherProps
  } = props;
  const [currentValue, setCurrentValue] = useState<any[]>(value);
  const cloneOptions = useMemo(() => lodash.cloneDeep(options), [options]);
  const [currentOptions, setCurrentOptions] = useState<any>(cloneOptions);
  const [selectStatus, setSelectStatus] = useState<
    '' | 'warning' | 'error' | undefined
  >(); // 组件当前状态，根据值是否在options中显示
  useEffect(() => {
    if (cloneOptions.length < maxLength || currentValue.length < maxLength) {
      let disabledFlag = false;
      cloneOptions.forEach((item: any) => {
        if (item.disabled) {
          disabledFlag = true;
          item.disabled = false;
        }
      });
      if (disabledFlag) setCurrentOptions([...cloneOptions]);
      return;
    }
    // 取消其他的选择
    if (currentValue.length === maxLength) {
      cloneOptions.forEach((item: any) => {
        if (currentValue.find((el: any) => el === item.value))
          item.disabled = false;
        else item.disabled = true;
      });
      setCurrentOptions([...cloneOptions]);
    }
  }, [currentValue, maxLength, cloneOptions]);
  useEffect(() => {
    setCurrentValue(value);
  }, [value]);
  useEffect(() => {
    let warningStatus = false;
    currentValue.forEach((item: any) => {
      if (
        currentValue.length &&
        !cloneOptions.find((el: any) => el.value === item)
      )
        warningStatus = true;
    });
    if (warningStatus) setSelectStatus('warning');
    else setSelectStatus(undefined);
  }, [cloneOptions, currentValue]);
  // 值类型发生变化
  const currentValueOnchange = (e: any) => {
    setCurrentValue(e);
    onChange?.(e);
  };
  return (
    <Select
      onChange={currentValueOnchange}
      value={currentValue || value}
      mode="multiple"
      status={selectStatus}
      {...originProps}
      {...otherProps}
      options={currentOptions}
    />
  );
};

export default MaxNumSelect;
